﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVC3DEMO.Models.Youtube;
using Google.YouTube;
using Google.GData.Client;
using MVC3DEMO.Models.Entities;
using Google.GData.Extensions.MediaRss;
using Google.GData.YouTube;
using Google.GData.Extensions.Location;
using MVC3DEMO.Models.Util;
using System.IO;


namespace MVC3DEMO.Controllers
{
    public class YoutubeController : Controller
    {
        //
        // GET: /Youtube/

        private static YouTubeVideoHelper youtubevdeo;
        public YoutubeController()
        {
            youtubevdeo = new YouTubeVideoHelper();
        }
        public ActionResult Index()
        {
            var list = YouTubeVideoHelper.GetVideos();
            foreach (YouTubeVideoObject video in list)
            {
                video.VideoId.ToString();
            }
            return View(list);
        }

        //
        // GET: /Youtube/Details/5
        public ActionResult Login()
        {


            Session["authSubUrl"] = Google.GData.Client.AuthSubUtil.getRequestUrl("http://localhost:7642/Youtube/Upload", "http://gdata.youtube.com", false, true);
            return View();
        }

        public ActionResult Success(int status, string id)
        {

            if (status != 200) // Upload was not successful. Checking the status code.
            {

                ViewData["UploadError"] = true;

                return RedirectToAction("Upload");

            }

            // Now you should store uploaded video information using your Data Access layer / Repository.
            // This is the place in which you should set Video ID returned back to this action from YouTube API.
            // This ID (in form of XXXXXXXXXXX) will be used to retrieve a video to edit or play.

            return RedirectToAction("Index");

        }
        private static string GetMimeType(string fileName)
        {
            string mimeType = "application/unknown";
            string ext = System.IO.Path.GetExtension(fileName).ToLower();
            Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
            if (regKey != null && regKey.GetValue("Content Type") != null)
                mimeType = regKey.GetValue("Content Type").ToString();
            return mimeType;
        }
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Upload(UploadViewModel uploadViewModel)
        {
            Uploader uploader = new Uploader();
            const string developerKey = "AI39si58Nz1BfWygZ3l5f1FcJUSU5B3LBW_luLry8fxwsmBurK-bCPuXNRolDpXY_PPMqNEBV7nmH3knZyujjHPLAZ6ITfuZaw";
            const string applicationName = "Video";
            YouTubeRequestSettings settings = new YouTubeRequestSettings(applicationName, developerKey, (string)Session["token"]);
            settings.Timeout = 999999889;
            YouTubeRequest request = new YouTubeRequest(settings);
            
            Video newVideo = new Video();
            uploader.UploadPath = Server.MapPath("~\\VideoUpload");
            bool success = uploader.DoUpload("Path");
            String fileupload = uploader.UploadedFile.FullPath;
            String filename = uploader.UploadedFile.FileName;
            newVideo.Title = uploadViewModel.Title;
            newVideo.Tags.Add(new Google.GData.Extensions.MediaRss.MediaCategory("Autos", Google.GData.YouTube.YouTubeNameTable.CategorySchema));
            newVideo.Keywords = uploadViewModel.Keywords;
            newVideo.Description = uploadViewModel.Description;


            // uploadViewModel.Path
            newVideo.Tags.Add(new Google.GData.Extensions.MediaRss.MediaCategory("mydevtag, anotherdevtag",
            Google.GData.YouTube.YouTubeNameTable.DeveloperTagSchema));

            newVideo.YouTubeEntry.Location = new Google.GData.Extensions.Location.GeoRssWhere(37, -122);
            // alternatively, you could just specify a descriptive string
            // newVideo.YouTubeEntry.setYouTubeExtension("location", "Mountain View, CA");



            // newVideo.YouTubeEntry.MediaSource = new Google.GData.Client.MediaFileSource(filename,uploadViewModel.Type);

            // Video createdVideo = request.Upload(newVideo);
            try
            {

                
                newVideo.YouTubeEntry.MediaSource = new MediaFileSource(fileupload, GetMimeType(filename));
                GDataRequestFactory gdrf =
(GDataRequestFactory)request.Service.RequestFactory;
                gdrf.Timeout = (7000) * 60 * 60 * 60;
                Video createvideo = request.Upload(newVideo);

                if (createvideo != null)
                {
                    String FileToDelete = uploader.UploadedFile.FullPath;
                    System.IO.File.Delete(FileToDelete);
                }
            }
            catch (Exception ex)
            {
            }


            return View();
          
        }
        public ActionResult Upload(string token)
        {
            Session["token"] = AuthSubUtil.exchangeForSessionToken(token, null);

            return View();
        }
        public ActionResult UploadYoutube()
        { return View(); }
        [HttpPost]
        public ActionResult UploadYoutube(UploadViewModel uploadViewModel)
        {

            YouTubeRequestSettings settings = new YouTubeRequestSettings("video", "AI39si58Nz1BfWygZ3l5f1FcJUSU5B3LBW_luLry8fxwsmBurK-bCPuXNRolDpXY_PPMqNEBV7nmH3knZyujjHPLAZ6ITfuZaw", "thanhluan.soft", "longthanhcamgiadongchaythoigian");

            
            YouTubeRequest request = new YouTubeRequest(settings);
            settings.Maximum = 8000000;
            settings.Timeout = 99999999;
            settings.

            HttpRuntime.UnloadAppDomain();
        

            Video newVideo = new Video();
            Uploader uploader = new Uploader();
            uploader.UploadPath = Server.MapPath("~\\VideoUpload");
            bool success = uploader.DoUpload("Path");
            String fileupload = uploader.UploadedFile.FullPath;
            String filename = uploader.UploadedFile.FileName;
            newVideo.Title = uploadViewModel.Title;
            newVideo.Tags.Add(new Google.GData.Extensions.MediaRss.MediaCategory("Autos",                                        Google.GData.YouTube.YouTubeNameTable.CategorySchema));
            newVideo.Keywords = "cars, funny";
            newVideo.Description = "My description";
            newVideo.YouTubeEntry.Private = false;
            newVideo.Tags.Add(new Google.GData.Extensions.MediaRss.MediaCategory("mydevtag, anotherdevtag",
              Google.GData.YouTube.YouTubeNameTable.DeveloperTagSchema));

            newVideo.YouTubeEntry.Location = new Google.GData.Extensions.Location.GeoRssWhere(37, -122);
            // alternatively, you could just specify a descriptive string
            // newVideo.YouTubeEntry.setYouTubeExtension("location", "Mountain View, CA");
            try
            {

                
                newVideo.YouTubeEntry.MediaSource = new MediaFileSource(fileupload, GetMimeType(filename));
                Video createvideo = request.Upload(newVideo);

                if (createvideo != null)
                {
                    String FileToDelete = uploader.UploadedFile.FullPath;
                    System.IO.File.Delete(FileToDelete);
                }
            }
            catch (Exception ex)
            {
            }


            return View();
        }
        public ActionResult Details(int id)
        {
            return View();
        }

        //
        // GET: /Youtube/Create

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Youtube/Create

        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Youtube/Edit/5

        public ActionResult Edit(int id)
        {
            return View();
        }

        //
        // POST: /Youtube/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Youtube/Delete/5

        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /Youtube/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}
